import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  // 创建jwt_token
  async createToken(userInfo) {
    // 将用户信息（userId、name）存放到 jwt 中
    return this.jwtService.sign(userInfo);
    // return {
    //   access_token: this.jwtService.sign(userInfo),
    // };
  }

  // 校验登录状态
  validateToken(token) {
    if (!token) {
      throw new HttpException(
        {
          statusCode: HttpStatus.UNAUTHORIZED,
          message: "token 为空",
          error: "Invalid Credentials",
        },
        HttpStatus.UNAUTHORIZED,
      );
    }
    try {
      return this.jwtService.verify(token);
    } catch {
      return false;
    }
  }
}
